
//计算x^n 直接乘n次 by MoreWindows( http://blog.csdn.net/MoreWindows )  
int power1(int x, unsigned int n)  
{  
    int result = 1;  
    while (n--)  
        result *= x;  
    return result;  
}  

//计算x^n 二分递归实现  by MoreWindows( http://blog.csdn.net/MoreWindows )  
int power2(int x, unsigned int n)  
{  
    if (n == 0)  
        return 1;  
    else if (n == 1)  
        return x;  
    else   
    {  
        if (n % 2 == 1)  
            return power2(x, n / 2) * power2(x, n / 2) * x;  
        else  
            return power2(x, n / 2) * power2(x, n / 2);  
    }  
}

//计算x^n   by MoreWindows( http://blog.csdn.net/MoreWindows )  
int power3(int x, unsigned int n)  
{  
    if (n == 0)  
        return 1;  
    int result = 1;  
    while (n != 0)  
    {  
        if ((n & 1) != 0)  
            result *= x;  
        x *= x;  
        n >>= 1;  
    }  
    return result;  
}  

//计算x^n  by MoreWindows( http://blog.csdn.net/MoreWindows )  
int power4(int x, unsigned int n)  
{  
    if (n == 0)  
    {  
        return 1;  
    }  
    else  
    {  
        while ((n & 1) == 0)  
        {  
            n >>= 1;  
            x *= x;  
        }  
    }  
    int result = x;  
    n >>= 1;  
    while (n != 0)  
    {     
        x *= x;  
        if ((n & 1) != 0)  
            result *= x;  
        n >>= 1;  
    }  
    return result;  
}  

int main()  
{  
    printf("验证power4()  -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");  
    for (int i = 0; i <= 10; i++)  
        printf("2的%d次方为\t%d\n", i, power4(2, i));  
    return 0;  
}
